package com.achievo.know.web.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class AuthFilter implements Filter {
	
	private String[] eurls;
	
	private String[] iurls;
	

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest r=(HttpServletRequest)request;
		String rurl=r.getRequestURI();
		if(eurls!=null && eurls.length>0){
			for(String url:eurls){
				if(rurl!=null){
					if(rurl.startsWith(r.getContextPath()+url)){
						HttpSession session=r.getSession();
						
						String loginuser=(String)session.getAttribute("loginuser");
						if(loginuser==null || "".equals(loginuser)){
							HttpServletResponse res=(HttpServletResponse)response;
							res.sendRedirect(r.getContextPath()+"/auth/login-logout.action");
						}
						break;
					}
				}
			}
		}
		if(rurl.startsWith("/knowledge")){
			rurl=rurl.replaceFirst("/knowledge", "");
			HttpServletResponse res=(HttpServletResponse)response;
			res.sendRedirect(rurl+"?"+r.getQueryString());
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String eurl=filterConfig.getInitParameter("excludeUrl");
		if(StringUtils.isNotEmpty(eurl)){
			eurls=eurl.split(",");
		}
		String iurl=filterConfig.getInitParameter("includeUrl");
		if(StringUtils.isNotEmpty(iurl)){
			iurls=iurl.split(",");
		}
		System.out.println("init");
	}

}
